package org.wattdepot.cli.commands;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;
import javax.xml.datatype.XMLGregorianCalendar;
import org.wattdepot.client.BadXmlException;
import org.wattdepot.client.MiscClientException;
import org.wattdepot.client.NotAuthorizedException;
import org.wattdepot.client.ResourceNotFoundException;
import org.wattdepot.client.WattDepotClient;
import org.wattdepot.util.tstamp.Tstamp;

/**
 * Provides the command to create the power generated chart.
 * 
 * @author David Joel Lazaro
 */
public class ChartPowerCommand implements Command {

  /**
   * Calls the chartPower method.
   * 
   * @param userInput The user input.
   * @param client The WattDepotClient
   * @return Returns the method call with the proper parameters.
   */
  public String doCommand(List<String> userInput, WattDepotClient client) {
    return chartPower(userInput, client);
  }

  /**
   * Writes out an html file that when displayed in a browser will show a chart representation of
   * the power generated (or consumed) by this source from startday to endday, where data points are
   * generated at a sampling interval of minutes.
   * 
   * @param commandParam The input from user.
   * @param client The WattDepotClient
   * @return Returns the power generated chart.
   */
  private String chartPower(List<String> commandParam, WattDepotClient client) {
    StringBuffer buff = new StringBuffer();
    SourceChecker check = new SourceChecker();
    TStampChecker stampCheck = new TStampChecker();
    if (!check.sourceChecker(commandParam.get(3), client)) {
      return "";
    }

    if (!stampCheck.checkTStamp(commandParam.get(4))
        || (!stampCheck.checkTStamp(commandParam.get(5)))) {
      return "ERROR: Timestamp error.";
    }

    try {
      FileWriter outputFile = new FileWriter(commandParam.get(9));
      BufferedWriter out = new BufferedWriter(outputFile);

      int interval = Integer.parseInt(commandParam.get(7));
      StringBuffer buffer = new StringBuffer(256);

      buffer.append("<html><body><img src="
          + "http://chart.apis.google.com/chart?chs=250x100&cht=lc&chd=t:");

      XMLGregorianCalendar start = Tstamp.makeTimestamp(commandParam.get(4));
      XMLGregorianCalendar end = Tstamp.makeTimestamp(commandParam.get(5));

      if (commandParam.get(2).equalsIgnoreCase("generated")) {
        while (!start.equals(end)) {
          double data = client.getPowerGenerated(commandParam.get(3), start) / 1000000;
          buffer.append(data);
          buffer.append(',');
          start = Tstamp.incrementMinutes(start, interval);
        }
      }
      else if (commandParam.get(2).equalsIgnoreCase("consumed")) {
        while (!start.equals(end)) {
          double data = client.getPowerConsumed(commandParam.get(3), start) / 1000000;
          buffer.append(data);
          buffer.append(',');
          start = Tstamp.incrementMinutes(start, interval);
        }
      }
      else {
        out.close();
        return "";
      }

      buffer.deleteCharAt(buffer.length() - 1);
      buffer.append("&chds=0.0,54.0&chxt=y&chxr=0,0.0,54.0></body></html>");
      out.write(buffer.toString());
      out.close();
    }
    catch (IOException e) {
      e.printStackTrace();
    }
    catch (NotAuthorizedException e) {
      e.printStackTrace();
    }
    catch (ResourceNotFoundException e) {
      e.printStackTrace();
    }
    catch (BadXmlException e) {
      e.printStackTrace();
    }
    catch (MiscClientException e) {
      e.printStackTrace();
    }
    catch (Exception e) {
      e.printStackTrace();
    }

    return buff.toString();
  }
}
